package com.wgts.wgts.mvp.view.activity.shopCar;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wgts.wgts.ActivityStack;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.eventbus.ShopCarEvent;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerShoppingCarComponent;
import com.wgts.wgts.dagger.module.ShoppingCarModule;
import com.wgts.wgts.mvp.presenter.IShoppingCarPersenter;
import com.wgts.wgts.mvp.view.IShoppingCarView;
import com.wgts.wgts.mvp.view.activity.affrimorder.AffirmOrderActivity;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.mvp.view.activity.pay.ContinuePayActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.AdvancedTaskActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.UpgradeShopKeeperActivity;
import com.wgts.wgts.netmodle.req.AffirmOrderProduct;
import com.wgts.wgts.netmodle.req.AffirmOrderRequest;
import com.wgts.wgts.netmodle.resp.ShopCarListEntity;
import com.wgts.wgts.tools.AppInfor;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/*
 *
 *
 *   data:2018/9/615:36
 *
 */public class ShoppingCarFragment extends LazyBaseFragment implements IShoppingCarView {
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.shopping_car_recycle)
    RecyclerView shoppingCarRecycle;
    @BindView(R.id.shopping_check_all)
    LinearLayout shoppingCheckAll;
    @BindView(R.id.shopping_all_price)
    TextView shoppingAllPrice;
    @BindView(R.id.go_pay)
    LinearLayout goPay;
    @BindView(R.id.shopping_buy_ly)
    LinearLayout shoppingBuyLy;
    @BindView(R.id.shopping_delete_ly)
    LinearLayout shoppingDeleteLy;
    Unbinder unbinder;
    @BindView(R.id.shopping_choose_number)
    TextView shoppingChooseNumber;
    @BindView(R.id.shopping_check_all_image)
    ImageView shoppingCheckAllImage;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.go_close_text)
    TextView goCloseText;
    @BindView(R.id.shop_bottom_ly)
    LinearLayout shopBottomLy;
    @BindView(R.id.none_data_ly)
    LinearLayout noneDataLy;
    @BindView(R.id.go_shop_ly)
    LinearLayout goShopLy;
    private ShopCarParentRecycleAdapter adapter;

    private Intent intent;

    private static boolean checkAll = false;
    private boolean isRight = false;

    private AffirmOrderRequest requests;
    private AffirmOrderProduct product;

    private ArrayList<Integer> arrayList;


    @Inject
    IShoppingCarPersenter persenter;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            persenter.getShopCarList();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.shopping_car_fragment, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        backBtnLy.setVisibility(View.INVISIBLE);
        includeTitle.setText("购物车");
        includeText.setText("编辑");
        return view;
    }

    @Override
    public void init() {
        DaggerShoppingCarComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .shoppingCarModule(new ShoppingCarModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void loadData() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.include_right_ly, R.id.shopping_check_all, R.id.go_pay, R.id.shopping_delete_ly,
            R.id.go_shop_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.include_right_ly:
                if (isRight) {
                    includeText.setText("编辑");
                    shoppingBuyLy.setVisibility(View.VISIBLE);
                    shoppingDeleteLy.setVisibility(View.GONE);
                    includeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.hint_6));
                    isRight = false;
                } else {
                    includeText.setText("保存");
                    shoppingBuyLy.setVisibility(View.GONE);
                    shoppingDeleteLy.setVisibility(View.VISIBLE);
                    includeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.price_text));
                    isRight = true;
                }
                break;
            case R.id.shopping_check_all:
                if (checkAll) {
                    persenter.checkAll(false);
                    persenter.totalPrice();
                    persenter.chooseNumber();
                    shoppingCheckAllImage.setSelected(false);
                    checkAll = false;
                } else {
                    persenter.checkAll(true);
                    persenter.totalPrice();
                    persenter.chooseNumber();
                    shoppingCheckAllImage.setSelected(true);
                    checkAll = true;
                }
                persenter.isAllCheck();
                break;
            case R.id.go_pay:
                persenter.goPay();
                break;
            case R.id.shopping_delete_ly:
                persenter.haveCheck();
                break;
            case R.id.go_shop_ly:
                for(BaseActivity activity : ActivityStack.getInstance().getActivities()){
                    if(activity != null && activity instanceof MoHuMainActivity){
                        ((MoHuMainActivity) activity).changeViewPage(0);
                    }
                }
                break;
        }
    }

    @Override
    public void dataComplete(List<ShopCarListEntity> listEntities) {
        if (listEntities.size() <= 0 || listEntities == null) {
            shopBottomLy.setVisibility(View.GONE);
            noneDataLy.setVisibility(View.VISIBLE);
            includeRightLy.setVisibility(View.INVISIBLE);
            includeText.setText("编辑");
            shoppingBuyLy.setVisibility(View.VISIBLE);
            shoppingDeleteLy.setVisibility(View.GONE);
            includeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.hint_6));
            isRight = false;
        } else {
            shopBottomLy.setVisibility(View.VISIBLE);
            noneDataLy.setVisibility(View.GONE);
            includeRightLy.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void totalPriceResult(Double price) {
        shoppingAllPrice.setText("合计：￥" + price);
    }

    @Override
    public void choosNumber(Integer number) {
        goCloseText.setText("(" + number + ")");
        //shoppingChooseNumber.setText("全选（" + number + "）");
    }

    @Override
    public void isAllCheck(boolean isAllCheck) {
        if (isAllCheck) {
            shoppingCheckAllImage.setSelected(true);
            checkAll = true;
        } else {
            shoppingCheckAllImage.setSelected(false);
            checkAll = false;
        }
    }

    @Override
    public void haveCheck(boolean haveCheck) {
        if (haveCheck) {
            ToastDate toastDate = new ToastDate();
            toastDate.setCancelQuestion("确认删除选中商品吗？");
            toastDate.setCancelText("删除");
            toastDate.setPointText("取消");
            toastDate.setFragmentManager(getFragmentManager());
            final ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
            fragment.show(getFragmentManager(), "deleteAllShopDialog");
            fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
                @Override
                public void onClickCancle() {
                    fragment.dismiss();
                }

                @Override
                public void onClickEnsuer() {
                    persenter.deleteAllShopping();
                    persenter.totalPrice();
                    persenter.chooseNumber();
                    persenter.isAllCheck();
                    fragment.dismiss();
                }
            });
        } else {
            Toast.makeText(getContext(), "您还未选中商品", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getShopCarList(List<ShopCarListEntity> shopCarListEntities) {
        shopBottomLy.setVisibility(View.VISIBLE);
        //购物车列表初始化底部栏数据清空
        checkAll = false;
        shoppingCheckAllImage.setSelected(false);
        goCloseText.setText("(0)");
        shoppingAllPrice.setText("合计：￥0.0");

        if (shopCarListEntities.size() <= 0 || shopCarListEntities == null) {
            shopBottomLy.setVisibility(View.GONE);
            noneDataLy.setVisibility(View.VISIBLE);
            includeRightLy.setVisibility(View.INVISIBLE);
            includeText.setText("编辑");
            shoppingBuyLy.setVisibility(View.VISIBLE);
            shoppingDeleteLy.setVisibility(View.GONE);
            includeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.hint_6));
        } else {
            includeRightLy.setVisibility(View.VISIBLE);
            shopBottomLy.setVisibility(View.VISIBLE);
            noneDataLy.setVisibility(View.GONE);
            shoppingCarRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
            adapter = new ShopCarParentRecycleAdapter(getContext(), shopCarListEntities, persenter, getFragmentManager());
            shoppingCarRecycle.setAdapter(adapter);
            adapter.setUpLevelClickListen(new ShopCarParentRecycleAdapter.upLevelClickListen() {
                @Override
                public void upLevelClick(View view, int position) {
                    if (AppInfor.getInstance().getUserState() < 4){
                        if (AppInfor.getInstance().getUserState() < 2) {
                            intent = new Intent(getActivity(), UpgradeShopKeeperActivity.class);
                        } else {
                            intent = new Intent(getActivity(), AdvancedTaskActivity.class);
                        }
                        startActivity(intent);
                    }
                }
            });
        }
    }

    @Override
    public void checkNotify() {
        adapter.checkNotify();
    }

    @Override
    public void numberNotify(int position) {
        adapter.numberNotify(position);
    }

    @Override
    public void goPay(ArrayList<ShopCarListEntity.product> list) {
        if (list.size() <= 0) {
            MoHuToast.showToast("您还未选中商品");
        } else {
            Intent intent = new Intent(getActivity(), AffirmOrderActivity.class);
            requests = new AffirmOrderRequest();
            requests.products = new ArrayList<>();
            arrayList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                product = new AffirmOrderProduct();
                product.productId = list.get(i).productId;
                product.productNum = list.get(i).productCount;
                product.skuId = list.get(i).skuId;
                product.activitySkuId = String.valueOf(list.get(i).activitySkuId);
                requests.products.add(product);
                arrayList.add(Integer.parseInt(list.get(i).cartId));
            }
            intent.putExtra(AffirmOrderActivity.Products, requests);
            intent.putIntegerArrayListExtra(AffirmOrderActivity.cartIdData, arrayList);
            startActivityForResult(intent, ContinuePayActivity.PAY_RESULT_OK);
        }
    }

    @Override
    public void shopCheck(int position) {
        adapter.shopCheck(position);
    }

    @Override
    public void onError(int status, String msg) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ContinuePayActivity.PAY_RESULT_OK && data != null) {
            persenter.getShopCarList();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ShopCarEvent event) {
        persenter.getShopCarList();
    }

}
